import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../bloc/report/report_bloc.dart';
import '../../bloc/report/report_data.dart';
import '../../bloc/report/report_event.dart';
import '../../utils/AuthService.dart';

// 定义颜色常量
const Color kBackgroundColor = Color(0xFFF7F9FC);
const Color kLightBlue = Color(0xFFE6F2FF);
const Color kBlue = Color(0xFF41C7DD);
const Color kDarkBlue = Color(0xFF268DFF);
const Color kTextLight = Color(0xFF6B7A8B);
const Color kTextLigh1t = Color(0xff000000);
const Color kDividerColor = Color(0xFFE0E0E0);

// void main() {
//   runApp(const MyApp());
// }

class ReportsNewPage extends StatelessWidget {
  const ReportsNewPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const OctopusReportPage();
  }
}

class OctopusReportPage extends StatefulWidget {
  const OctopusReportPage({super.key});

  @override
  State<OctopusReportPage> createState() => _OctopusReportPageState();
}

class _OctopusReportPageState extends State<OctopusReportPage> {
  int _selectedProfitYear = 2024;
  // int _selectedTaxYear = 2024;

  @override
  void initState() {
    super.initState();
    _selectedProfitYear = DateTime.now().year;

    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ReportBloc>().add(ReportChartEvent(_selectedProfitYear));
    });
   }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('章鱼问账'),
        elevation: 0,
        backgroundColor:  Color(0xFFD6EFFF),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFD6EFFF),Color(0xCCAACDDA)],
            stops: [0.0, 1.0],
          ),
        ),
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 20),
                _buildTopNavigation(),
                const SizedBox(height: 20),

                BlocConsumer<ReportBloc, ReportState>(
                  buildWhen: (previous, current) {
                    return current is ReportChartSuccess;
                  },
                  builder: (context, state) {
                    if (state is ReportChartSuccess) {
                      var data1=  (state.reportData as Map<String, dynamic>)['利润趋势图'];
                      var data2=  (state.reportData as Map<String, dynamic>)['纳税分析图'];
                      List<dynamic>? list1 = data1 ;
                      List<dynamic>? list2 = data2 ;

                      // 计算最大值
                      double maxY1 = (list1 != null && !list1.isEmpty
                          ? list1.where((item) => item is num).map((item) => (item as num).abs().toDouble()).reduce(math.max)
                          : 0.0) + 4.0;
                      double maxY2 = (list2 != null && !list2.isEmpty
                          ? list2.where((item) => item is num).map((item) => (item as num).abs().toDouble()).reduce(math.max)
                          : 0.0)+4.0;

                      print( 'maxY1: $maxY1');
                      print( 'maxY2: $maxY2');



                      return Column(
                        children: [
                          // _getChartData
                          _buildChartSection(
                            maxY:  maxY1,
                            title: '利润趋势图',
                            selectedYear: _selectedProfitYear,
                            onYearSelected: (year) {
                              setState(() {
                                _selectedProfitYear = year;
                                context.read<ReportBloc>().add(ReportChartEvent(_selectedProfitYear));
                              });
                            },
                            chartData: _getChartData(data1),
                          ),
                          const SizedBox(height: 20),
                          _buildChartSection(
                            maxY:  maxY2,
                            title: '纳税分析图',
                            selectedYear: _selectedProfitYear,
                            onYearSelected: (year) {
                              setState(() {
                                _selectedProfitYear = year;
                                context.read<ReportBloc>().add(ReportChartEvent(_selectedProfitYear));
                              });
                            },
                            chartData: _getChartData(data2),
                          ),
                          const SizedBox(height: 20),
                          _buildEvaluationReport(),
                          const SizedBox(height: 20),

                        ],
                      );
                    }
                    return Container();
                  },
                  listener: (context, state) {
                    if (state is ReportChartSuccess) {
                      // setState(() {
                      //   _selectedProfitYear = state.reportData['year'] ?? 2024;
                      // });
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTopNavigation() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildNavItem(Icons.bar_chart_sharp, '利润表',(){
            context.push('/report_income_statement');
          }),
          _buildNavItem(Icons.monetization_on, '资产负债表',(){
            context.push('/report_balance_sheet');
          }),
          _buildNavItem(Icons.analytics_outlined, '纳税报表',(){
            context.push('/report_tax_detail');
          }),
        ],
      ),
    );
  }

  Widget _buildNavItem(IconData icon, String label,GestureTapCallback callBack) {
    return GestureDetector(
      onTap: callBack,
      child: Column(
        children: [
          Icon(icon, size: 25, color: kTextLight),
          const SizedBox(height: 6),
          Text(label, style: const TextStyle(color: kTextLigh1t,fontSize: 12)),
        ],
      ),
    );
  }

  Widget _buildChartSection({
    double maxY = 0,
    required String title,
    required int selectedYear,
    required Function(int) onYearSelected,
    required List<FlSpot> chartData,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle(title),
          const SizedBox(height: 12),
          _buildYearSelector(selectedYear, onYearSelected),
          const SizedBox(height: 24),
          Padding(
            padding: const EdgeInsets.only(right: 26.0),
            child: SizedBox(
              height: 200,
              child: LineChart(
                _buildLineChartData(chartData,maxY),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Row(
      children: [
        Container(
          width: 4,
          height: 18,
          color: kBlue,
          margin: const EdgeInsets.only(right: 8),
        ),
        Text(
          title,
          style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }

  Widget _buildYearSelector(int selectedYear, Function(int) onYearSelected) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: Container(
          height: 21,
          decoration: BoxDecoration(
            color: kLightBlue,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Expanded(
                  flex: 1,
                  child: _buildYearItem(2023, selectedYear, onYearSelected)),
              Expanded(
                  flex: 1,
                  child: _buildYearItem(2024, selectedYear, onYearSelected)),
              Expanded(
                  flex: 1,
                  child: _buildYearItem(2025, selectedYear, onYearSelected)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildYearItem(int year, int selectedYear, Function(int) onYearSelected) {
    final bool isSelected = year == selectedYear;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => onYearSelected(year),
      child: Container(
        constraints: const BoxConstraints.expand(),
        alignment: Alignment.center,
        decoration: isSelected
            ? BoxDecoration(
          color: kBlue,
        )
            : null,
        child: Text(
          '$year',
          style: TextStyle(
            fontSize: 11,
            color: isSelected ? Colors.white : kTextLight,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  LineChartData _buildLineChartData(List<FlSpot> data,double maxY) {

    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawHorizontalLine: true,
        getDrawingHorizontalLine: (value) => FlLine(
          color: kDividerColor,
          strokeWidth: 1,
        ),
        drawVerticalLine: false,
      ),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 30,
            // 确保 sideTitles 的 getTitlesWidget 函数正确返回 SideTitleWidget
            getTitlesWidget: (double value, TitleMeta meta) {
              const titles = ['第一季度', '第二季度', '第三季度', '第四季度'];
              return SideTitleWidget(
                meta: meta,
                space: 1,
                child: Text(titles[value.toInt()], style: const TextStyle(fontSize: 10, color: kTextLight)),
              );
            },
            interval: 1,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 45,
            getTitlesWidget: (double value, TitleMeta meta) {
              // if (value % 4 != 0) return const SizedBox.shrink();
              return SideTitleWidget(
                meta: meta,
                space: 5,
                child: Text('${value.toInt()}', style: const TextStyle(fontSize: 10, color: kTextLight)),
              );
            },
            interval: maxY/4.0,
          ),
        ),
        rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
      ),
      borderData: FlBorderData(
        show: true,
        // border: Border.all(color: kDividerColor, width: 1),
        border: Border.symmetric(
          horizontal: BorderSide(color: kDividerColor, width: 1),
        ),
      ),
      minX: 0,
      maxX: 3,
      minY: 0,
      maxY: maxY  ,
      lineBarsData: [
        LineChartBarData(
          spots: data,
          isCurved: true,
          // isStrokeJoinRound: true,
          // isStrokeCapRound: true,
          curveSmoothness: 0.1,
          color: kBlue,
          barWidth: 3,
          belowBarData: BarAreaData(
            show: false,
            gradient: LinearGradient(
              colors: [
                kBlue.withOpacity(0.5),
                kLightBlue.withOpacity(0.1),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          dotData: FlDotData(
            show: false,
            getDotPainter: (spot, percent, barData, index) {
              return FlDotCirclePainter(
                radius: 4,
                color: kBlue,
                strokeWidth: 2,
                strokeColor: Colors.white,
              );
            },
          ),
        ),
      ],
    );
  }

  List<FlSpot> _getChartData(List<dynamic>? list) {
    return [
      FlSpot(0, (list?[0] ?? 0).abs().toDouble()),
      FlSpot(1, (list?[1] ?? 0).abs().toDouble()),
      FlSpot(2, (list?[2] ?? 0).abs().toDouble()),
      FlSpot(3, (list?[3] ?? 0).abs().toDouble()),
    ];
  }


  Widget _buildEvaluationReport() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
      decoration: BoxDecoration(
        color: kLightBlue,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '企业税务风险检测报告',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: kDarkBlue,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 8,bottom: 8),
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 3),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [kBlue, kDarkBlue],
              ),
              borderRadius: BorderRadius.circular(20),
            ),
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                AuthService().notifyGoThree();
              },
              child: const Text(
                '开始评估',
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}